﻿using System;
using System.Windows;
using System.Windows.Input;
using MDCAdminTool.Controls;

namespace MDCAdminTool.Commands
{
    public class AddCacheName : AsyncCommandBindingBase
    {
        public AddCacheName()
        {
            Command = Application.Current.Resources["AddCacheName"] as ICommand;
        }

        protected override void OnExecuted( object sender , ExecutedRoutedEventArgs e )
        {
            CacheHost host = null;

            if (e.Parameter is CacheCluster || e.Parameter is GroupBase)
            {
                CacheCluster cluster = e.Parameter as CacheCluster;

				if (cluster == null)
				{
					var @base = e.Parameter as GroupBase;
					if (@base != null)
					{
						cluster = @base.Cluster;
					}
					else
					{
						return;
					}
				}

                if (cluster.Hosts.Count != 0)
                    host = cluster.Hosts[0];
            } 
            else if( e.Parameter is CacheHost)
                host = e.Parameter as CacheHost;
            else if ( e.Parameter is MdcCache )
                host = (e.Parameter as MdcCache).Parent;

            if ( host != null )
            {
                NewCacheNameWin win = null;

                Application.Current.Dispatcher.Invoke(
                    new Action(
                        () =>
                            {
                                win = new NewCacheNameWin();
                                win.ShowDialog();
                            }
                        ));

				if (win.IsReady)
				{
					host.AddCacheName(win.CacheName, win.IsHighAvailability, win.NotificationsEnabled, win.Eviction, win.TTL,
					                  win.IsExpirable);
				}

            	Application.Current.Dispatcher.Invoke(
                    new Action(() => win.Close()));
            }
        }
        protected override void OnCanExecute( object sender , CanExecuteRoutedEventArgs e )
        {
            e.CanExecute = true;
        }
    }
}